import { defineStore } from 'pinia';
import { isSmallScreen } from '@/utils/verify';
import { SidebarCollapseStorage } from '@/utils/storage/localStorage';
import { type ProductPriceInfo, getProductPriceInfoAxios } from '@/api/product-management';

// eslint-disable-next-line no-use-before-define
export type AppStore = ReturnType<typeof useAppStore>;

/**
 * 注册app相关的store
 */
export const useAppStore = defineStore('app', {
  state: () => ({
    /** 是否关闭侧边栏 */
    sidebarCollapse: isSmallScreen() ? false : [null, true].includes(new SidebarCollapseStorage().get()),
    /** 模拟 UUID */
    baseID: 1,
    /** 价格列表 */
    priceList: null as { val: number }[] | null,
    /** 人民币兑换多少K币 */
    priceRate: null as number | null,
    /** 首页的路由 */
    homeRoute: '/home',
  }),
  actions: {
    /** 关闭或开启侧边栏 */
    setSideBarState(state?: boolean) {
      this.sidebarCollapse = typeof state === 'boolean' ? state : !this.sidebarCollapse;
    },
    /** 得到模拟的UUID */
    getBaseID(): number {
      this.baseID++;
      return this.baseID;
    },

    async getProductPriceInfo(): Promise<ProductPriceInfo> {
      if (typeof this.priceRate === 'number' && this.priceRate > 0 && Array.isArray(this.priceList) && this.priceList.length > 0) {
        return Promise.resolve({ priceRate: this.priceRate, priceList: this.priceList });
      } else {
        try {
          const res = await getProductPriceInfoAxios();
          this.priceRate = typeof res.data.priceRate === 'number' && res.data.priceRate > 0 ? res.data.priceRate : null;
          this.priceList = Array.isArray(res.data.priceList) && res.data.priceList.length > 0 ? res.data.priceList : null;
          if (this.priceList && this.priceRate) {
            return Promise.resolve({ priceRate: this.priceRate, priceList: this.priceList });
          } else {
            return Promise.reject({ code: -1002, msg: '获取信息失败,-P10002' });
          }
        } catch (error) {
          return Promise.reject({ code: error.code || -1001, msg: error.msg || '获取信息失败,-P10001' });
        }
      }
    },

    /** 设置首页的路由 */
    setHomeRoute(homeRoute: string) {
      this.homeRoute = homeRoute || '/home';
    },
  },
});
